<script setup>
import { ref, onMounted } from 'vue'
import { fetchAIResponse } from './services/aiService.js'

const question = ref('')
const messages = ref([])
const isLoading = ref(false)
const inputDisabled = ref(false)

// 模拟搜索结果数据
const searchResults = ref([])

// 发送问题
const sendQuestion = async () => {
  if (!question.value.trim() || isLoading.value) return
  
  // 添加用户问题到消息列表
  const userMessage = {
    id: Date.now(),
    type: 'user',
    content: question.value.trim()
  }
  messages.value.push(userMessage)
  
  // 添加AI回答占位符
  const aiMessage = {
    id: Date.now() + 1,
    type: 'ai',
    content: '',
    isStreaming: true
  }
  messages.value.push(aiMessage)
  
  isLoading.value = true
  inputDisabled.value = true
  question.value = ''
  
  try {
    // 调用AI服务获取回答
    await fetchAIResponse(userMessage.content, (chunk) => {
      // 流式更新回答内容
      aiMessage.content += chunk
    }, (results) => {
      // 更新搜索结果
      searchResults.value = results
    })
  } catch (error) {
    aiMessage.content = `很抱歉，获取回答失败：${error.message}`
    console.error('AI请求错误:', error)
  } finally {
    aiMessage.isStreaming = false
    isLoading.value = false
    inputDisabled.value = false
    
    // 滚动到底部
    setTimeout(() => {
      const chatContainer = document.querySelector('.chat-container')
      if (chatContainer) {
        chatContainer.scrollTop = chatContainer.scrollHeight
      }
    }, 100)
  }
}

// 处理键盘事件
const handleKeyPress = (e) => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault()
    sendQuestion()
  }
}

// 初始化示例消息
onMounted(() => {
  messages.value = [
    {
      id: 1,
      type: 'ai',
      content: '你好！我是AI智能问答助手，我可以帮你解答问题并进行联网搜索。请输入你的问题吧！',
      isStreaming: false
    }
  ]
})
</script>

<template>
  <div class="app-container">
    <header class="app-header">
      <h1>AI智能问答助手</h1>
      <p class="subtitle">支持联网搜索和流式回答</p>
    </header>
    
    <main class="app-main">
      <div class="chat-container">
        <div v-for="message in messages" :key="message.id" 
             :class="['message', `message-${message.type}`]">
          <div class="message-avatar">
            {{ message.type === 'user' ? '👤' : '🤖' }}
          </div>
          <div class="message-content">
            <p>{{ message.content }}
              <span v-if="message.isStreaming" class="typing-indicator">
                <span>.</span><span>.</span><span>.</span>
              </span>
            </p>
          </div>
        </div>
      </div>
      
      <div v-if="searchResults.length > 0" class="search-results">
        <h3>相关搜索结果</h3>
        <div class="results-list">
          <div v-for="(result, index) in searchResults" :key="index" class="search-result-item">
            <a :href="result.url" target="_blank" class="result-title">{{ result.title }}</a>
            <p class="result-snippet">{{ result.snippet }}</p>
            <a :href="result.url" target="_blank" class="result-url">{{ result.url }}</a>
          </div>
        </div>
      </div>
    </main>
    
    <footer class="app-footer">
      <div class="input-container">
        <textarea 
          v-model="question" 
          :disabled="inputDisabled"
          @keydown="handleKeyPress"
          placeholder="请输入你的问题...\n(按Enter发送，Shift+Enter换行)"
          rows="3"
          class="question-input"
        ></textarea>
        <button 
          @click="sendQuestion"
          :disabled="isLoading || !question.value || !question.value.trim()"
          class="send-button"
        >
          {{ isLoading ? '发送中...' : '发送' }}
        </button>
      </div>
    </footer>
  </div>
</template>

<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
}

.app-header {
  text-align: center;
  margin-bottom: 20px;
}

.app-header h1 {
  margin: 0 0 10px 0;
  font-size: 2rem;
  color: #333;
}

.subtitle {
  margin: 0;
  color: #666;
  font-size: 1rem;
}

.app-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  gap: 20px;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  border-radius: 10px;
  background-color: #f5f5f5;
  margin-bottom: 20px;
}

.message {
  display: flex;
  margin-bottom: 20px;
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.message-user {
  flex-direction: row-reverse;
}

.message-avatar {
  font-size: 2rem;
  margin: 0 10px;
  flex-shrink: 0;
}

.message-content {
  max-width: 70%;
  padding: 15px 20px;
  border-radius: 18px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.message-user .message-content {
  background-color: #007bff;
  color: white;
}

.typing-indicator span {
  animation: typing 1.4s infinite;
  opacity: 0;
}

.typing-indicator span:nth-child(2) { animation-delay: 0.2s; }
.typing-indicator span:nth-child(3) { animation-delay: 0.4s; }

@keyframes typing {
  0% { opacity: 0; }
  50% { opacity: 1; }
  100% { opacity: 0; }
}

.search-results {
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  max-height: 300px;
  overflow-y: auto;
}

.search-results h3 {
  margin-top: 0;
  color: #333;
  font-size: 1.2rem;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.search-result-item {
  padding: 10px;
  border-left: 3px solid #007bff;
  transition: all 0.2s ease;
}

.search-result-item:hover {
  background-color: #f9f9f9;
  transform: translateX(5px);
}

.result-title {
  color: #007bff;
  text-decoration: none;
  font-weight: bold;
  display: block;
  margin-bottom: 5px;
}

.result-title:hover {
  text-decoration: underline;
}

.result-snippet {
  margin: 5px 0;
  color: #333;
  font-size: 0.9rem;
}

.result-url {
  color: #28a745;
  text-decoration: none;
  font-size: 0.8rem;
}

.input-container {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

.question-input {
  flex: 1;
  padding: 15px;
  border: 2px solid #ddd;
  border-radius: 10px;
  font-size: 1rem;
  resize: vertical;
  min-height: 80px;
  max-height: 200px;
}

.question-input:focus {
  outline: none;
  border-color: #007bff;
}

.send-button {
  padding: 15px 30px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.send-button:hover:not(:disabled) {
  background-color: #0056b3;
}

.send-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }
  
  .message-content {
    max-width: 85%;
  }
  
  .input-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .send-button {
    width: 100%;
  }
}
</style>
